#include <QString>
#include <iostream>
#include "objectTreeItem.h"
#include "defines/primitive.h"
#include "vertexTreeItem.h"
#include "edgeTreeItem.h"
#include "faceTreeItem.h"

ObjectTreeItem::ObjectTreeItem(QTreeWidgetItem *_parentItem, Object *_obj, unsigned int) : TreeItem(_parentItem), obj(_obj){
    setExpanded(true);

    QString str = "Objeto ";
//    switch(_type)
//    {
//        case POLYGON:
//        {
//            str.append(QString::fromUtf8("Polígono "));
//            break;
//        }
//    }

    str.append(QString::number(obj->getId()));
    setText(0, str);

    appendChild();
}

ObjectTreeItem::~ObjectTreeItem(){
    for(int i = 0; i < childCount(); i++)
        delete child(i);

    delete obj;
}

Object *ObjectTreeItem::getObject(){
    return obj;
}

void ObjectTreeItem::select(bool _b){
    obj->select(_b);
}

void ObjectTreeItem::updateFaces(){
    int size = child(2)->childCount();
    for(int i = 0; i < size; i++)
    {
        QTreeWidgetItem *item = child(2)->child(i);
        Face *f = ((FaceTreeItem *)item)->getFace();
        item->setSelected(f->isSelected());
    }
}

void ObjectTreeItem::updateEdges(){
    int size = child(1)->childCount();
    for(int i = 0; i < size; i++)
    {
        QTreeWidgetItem *item = child(1)->child(i);
        Edge *e = ((EdgeTreeItem *)item)->getEdge();
        item->setSelected(e->isSelected());
    }
}

void ObjectTreeItem::updateVertices(){
    int size = child(0)->childCount();
    for(int i = 0; i < size; i++)
    {
        QTreeWidgetItem *item = child(0)->child(i);
        Vertex *v = ((VertexTreeItem *)item)->getVertex();
        item->setSelected(v->isSelected());
    }
}

void ObjectTreeItem::appendChild(){
    TreeItem *parent = new TreeItem(QString::fromUtf8("Vértices"), this);
    unsigned int size = obj->getVerticesSize();
    for(unsigned int i = 0; i < size; i++)
    {
        Vertex *v = obj->getVertex(i);
        new VertexTreeItem(parent, v);
    }

    parent = new TreeItem(QString::fromUtf8("Arestas"), this);
    size = obj->getEdgesSize();
    for(unsigned int i = 0; i < size; i++)
    {
        Edge *e = obj->getEdge(i);
        new EdgeTreeItem(parent, e);
    }

    parent = new TreeItem(QString::fromUtf8("Faces"), this);
    size = obj->getFacesSize();
    for(unsigned int i = 0; i < size; i++)
    {
        Face *f = obj->getFace(i);
        new FaceTreeItem(parent, f);
    }
}

void ObjectTreeItem::update(){
    for(int i = childCount(); i > 0 ; i--)
    {
        QTreeWidgetItem *item = child(i - 1);
        removeChild(item);
        delete item;
    }

    appendChild();
}
